//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using OpenLS.Spreadsheet.Parsing;

namespace OpenLS.Spreadsheet.Expressions
{
    internal class CellReferenceToken: ReferenceToken
    {
        private readonly int _row;
        private readonly bool _lockRow;
        private readonly int _column;
        private readonly bool _lockColumn;

#if DEBUG
        [ContractInvariantMethod]
        private  void ObjectInvariant()
        {
            Contract.Invariant(_row >= 0);
            Contract.Invariant(_column >= 0);
        }
#endif
        public CellReferenceToken(int row, bool lockRow, int column, bool lockColumn)
        {
            Contract.Requires(row >= 0);
            Contract.Requires(column >= 0);

            _row = row;
            _lockRow = lockRow;
            _column = column;
            _lockColumn = lockColumn;
        }

        public bool LockColumn
        {
            get { return _lockColumn; }
        }

        public int Column
        {
            get { return _column; }
        }

        public bool LockRow
        {
            get { return _lockRow; }
        }

        public int Row
        {
            get { return _row; }
        }

        public override string ToString()
        {
            return GetText(CellNamingConventions.A1NamingConvention);
        }
        public CellReference Project(Worksheet worksheet)
        {
            Contract.Requires(worksheet != null);
            //\\ sure about dynamic?
            return new DynamicCellReference(new AnchoredRowReference(worksheet.Rows[Row], LockRow),
                                            new AnchoredColumnReference(worksheet.Columns[this.Column], LockColumn));
        }

        public CellReferenceToken Offset(CellRelativeAddress address)
        {
            return new CellReferenceToken(LockRow? Row:Row+address.Row, LockRow, LockColumn?this.Column:Column + address.Column, LockColumn);
        }

        public override string GetText(CellNamingConvention convention)
        {
            return convention.GetText(this);
        }
    }
}